//
//  EFLoginViewController.m
//  EFHealth
//
//  Created by heng on 15-1-8.
//  Copyright (c) 2015年 ef. All rights reserved.
//


#import "EFLoginModel.h"
#import "EFCodeLoginModel.h"
#import "EFSendMsgModel.h"
#import "EFTabBarController.h"
#import "LoginViewController.h"
#import "AFNetworking.h"
#import <objc/runtime.h>
#import "AFHTTPSessionManager.h"
#import <CommonCrypto/CommonDigest.h>

@interface LoginViewController ()<UITextFieldDelegate,UIScrollViewDelegate,BaseModelProtocol>

@property (nonatomic,strong)EFTabBarController *tabbar ;

@property (nonatomic,strong)EFSendMsgModel *msgModel;
@property (nonatomic,strong)EFLoginModel *loginModel ;
@property (nonatomic,strong)EFCodeLoginModel *codeLoginModel ;

@property (nonatomic,strong)UIView *accountBgView;
@property (nonatomic,strong)UITextField *accountTextField;
@property (nonatomic,strong)UIView *passwordBgView;
@property (nonatomic,strong)UITextField *passwordTextField;
@property (nonatomic,strong)UIView *codeBgView;
@property (nonatomic,strong)UITextField *codeTextField;
@property (nonatomic,strong)UIScrollView *bgScrollView ;
@property (nonatomic,strong)UIView *logoImageBgView ;
@property (nonatomic,strong)UIView *logBgView ;

@property(nonatomic, strong)UIButton *pwdCodeSwitchBtn;
@property(nonatomic, assign)BOOL isPwdLogin;
@property(nonatomic, strong)UIButton *sendMessageBtn;
@property (nonatomic,strong) NSTimer  *getCodeTimer ;
@property (nonatomic,assign) int timeCount ;

@end

@implementation LoginViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    self.navigationController.navigationBarHidden = YES;
}

- (void)initView
{
    [super initView];
    
    [self.view addSubview:self.bgScrollView];
    [self.bgScrollView addSubview:self.logoImageBgView];
    [self.bgScrollView addSubview:self.logBgView];
    self.isPwdLogin = YES;
    self.timeCount = 60;
}

- (void)loginBtnClick{
    
//    self.accountTextField.text = @"15055009541";
//    self.passwordTextField.text = @"Aa12345678";
    
    if (ISEMPTY(self.accountTextField.text)) {
        [EFShowView showText:@"请输入手机号"];
        return;
    }
    
    if (self.accountTextField.text.length != 11) {
        [EFShowView showText:@"手机号长度不正确！"];
        return;
    }
        
    if(self.isPwdLogin){
        if (ISEMPTY(self.passwordTextField.text)){
            [EFShowView showText:@"请输入密码"];
            return;
        }
        [self showHUDWithLabel:@"登录中..."];
        [self.loginModel loginWith:self.accountTextField.text password:[self SHA256WithKey:self.passwordTextField.text]];
    //    [UIApplication sharedApplication].keyWindow.rootViewController = self.tabbar;
    }else{
        if (ISEMPTY(self.codeTextField.text)){
            [EFShowView showText:@"请输入验证码"];
            return;
        }
        [self showHUDWithLabel:@"登录中..."];
        [self.codeLoginModel loginWith:self.accountTextField.text code:self.codeTextField.text];
    }
}

- (void)getDataFinish:(BaseModel *)baseModel netResponse:(BaseResponse *)response{

    [self hideHUD];
    
    EFAppContext *appc = [EFAppContext sharedContext];
    if ([baseModel isKindOfClass:[EFSendMsgModel class]]) {
        
        [EFShowView showStatus:ShowSuccess text:@"验证码已发送"  InView:self.view];
        
        self.getCodeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFire) userInfo:nil repeats:YES];
        [self.getCodeTimer fire];
        
    }
    else if ([baseModel isKindOfClass:[EFLoginModel class]])
    {
        LoginResponse *resp = (LoginResponse*)response;
        LoginData *data = resp.resObject;
        appc.ACCESS_TOKEN = data.eid;
        appc.memberId = data.eid;
        appc.authorization = data.eid;
        appc.mobile = data.mobile;
        appc.unitId = data.unitId;
        [appc save];
        [UIApplication sharedApplication].keyWindow.rootViewController = self.tabbar;
    }
    else if([baseModel isKindOfClass:[EFCodeLoginModel class]])
    {
        CodeLoginResponse *resp = (CodeLoginResponse*)response;
        CodeLoginData *data = resp.resObject;
        appc.ACCESS_TOKEN = data.eid;
        appc.memberId = data.eid;
        appc.authorization = data.eid;
        appc.mobile = data.mobile;
        appc.unitId = data.unitId;
        [appc save];
        [UIApplication sharedApplication].keyWindow.rootViewController = self.tabbar;
    }
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)timerFire
{
    [_sendMessageBtn setHidden:NO];
    _sendMessageBtn.userInteractionEnabled = NO ;
    [_sendMessageBtn setTitle:[NSString stringWithFormat:@"重发( %d s)",self.timeCount--] forState:UIControlStateNormal];
    
    if (_timeCount<0) {
        _timeCount = 60 ;
        _sendMessageBtn.userInteractionEnabled = YES ;
        [_sendMessageBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.getCodeTimer invalidate]; self.getCodeTimer = nil;
    }
}

- (void)pwdCodeSwitchBtnClick{
    
    self.isPwdLogin = !self.isPwdLogin;
    if(self.isPwdLogin){
        [self.passwordBgView setHidden:NO];
        [self.codeBgView setHidden:YES];
        [_sendMessageBtn setHidden:YES];
        [_pwdCodeSwitchBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
    }else{
        [self.passwordBgView setHidden:YES];
        [self.codeBgView setHidden:NO];
        [_sendMessageBtn setHidden:NO];
        [_pwdCodeSwitchBtn setTitle:@"密码登录" forState:UIControlStateNormal];
    }
}

- (void)sendMessageClick:(UIButton *)btn{
    if(ISEMPTY(self.accountTextField.text)){
        [EFShowView showText:@"请输入手机号"];
        return;
    }

    [self.msgModel getSendMessageWithMobile:self.accountTextField.text];
}

- (void)getDataFinish:(BaseModel *)baseModel netError:(NSError *)error{
    [self hideHUD];
    [EFShowView showErrorText:error.domain];
    NSLog(@"%@",error.domain);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}

- (UIScrollView *)bgScrollView{
    
    if (nil == _bgScrollView) {
        _bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _bgScrollView.delegate = self ;
        _bgScrollView.contentSize = CGSizeMake(0, isIphone4 ? 400 : 0);
//        _bgScrollView.alwaysBounceVertical = YES ;
    }
    return _bgScrollView;
}

- (UIView *)logoImageBgView{
    
    if (nil == _logoImageBgView) {
        
        _logoImageBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
        UIImageView *bgImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
        bgImage.image = kImage(@"login_top");
        [_logoImageBgView addSubview:bgImage];
        
        UIImageView *logomage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 128, 55)];
        logomage.image = kImage(@"img_logo");
        logomage.center = _logoImageBgView.center;
        [_logoImageBgView addSubview:logomage];
    }
    return _logoImageBgView;
}

- (UIView *)accountBgView{
    if (nil == _accountBgView) {
        _accountBgView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, _logBgView.width-40, 40)];
        [_accountBgView setViewEdgeWithBorderWidth:0.5 cornerRadius:3 borderColor:[UIColor grayColor]];
        
        UILabel *leftLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 40, _accountBgView.height)];
        leftLab.text = @"+86";
        leftLab.textColor = kTitleColor_midden;
        leftLab.font = kFontMidden;
        [_accountBgView addSubview:leftLab];
        
        _accountTextField = [[UITextField alloc] initWithFrame:CGRectMake(leftLab.right, 0, _accountBgView.width-60, _accountBgView.height)];
        _accountTextField.placeholder = @"请输入手机号";
        _accountTextField.delegate = self;
        _accountTextField.textColor = kTitleColor_light;
        _accountTextField.font = kFontMidden;
        if (@available(iOS 13.0,*)) {
            Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
            UILabel *placeholderLabel = object_getIvar(_accountTextField, ivar);
            placeholderLabel.textColor = kTitleColor_light;
            placeholderLabel.font = [UIFont boldSystemFontOfSize:14];
        }else{
            [_accountTextField setValue:kTitleColor_light forKeyPath:@"_placeholderLabel.textColor"];
        }
        _accountTextField.keyboardType = UIKeyboardTypePhonePad;
        _accountTextField.clearButtonMode=UITextFieldViewModeAlways;
        [_accountBgView addSubview:_accountTextField];

    }
    return _accountBgView;
}

- (UIView *)passwordBgView{
    if (nil == _passwordBgView) {
        _passwordBgView = [[UIView alloc] initWithFrame:CGRectMake(20, _accountBgView.bottom+16, _accountBgView.width, _accountBgView.height)];
        [_passwordBgView setViewEdgeWithBorderWidth:0.5 cornerRadius:3 borderColor:[UIColor grayColor]];
        
        _passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, _passwordBgView.width-10, _passwordBgView.height)];
        _passwordTextField.placeholder = @"请输入密码";
        _passwordTextField.textColor = kTitleColor_light;
        _passwordTextField.delegate = self;
        _passwordTextField.font = kFontMidden;
        if (@available(iOS 13.0,*)) {
            Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
            UILabel *placeholderLabel = object_getIvar(_passwordTextField, ivar);
            placeholderLabel.textColor = kTitleColor_light;
            placeholderLabel.font = [UIFont boldSystemFontOfSize:14];
        }else{
            [_passwordTextField setValue:kTitleColor_light forKeyPath:@"_placeholderLabel.textColor"];
        }
//        _passwordTextField.keyboardType = UIKeyboardTypeNumberPad;
        _passwordTextField.returnKeyType=UIReturnKeyDone;
        [_passwordBgView addSubview:_passwordTextField];

    }
    return _passwordBgView;
}

- (UIView *)codeBgView{
    if (nil == _codeBgView) {
        _codeBgView = [[UIView alloc] initWithFrame:CGRectMake(20, _accountBgView.bottom+16, _accountBgView.width, _accountBgView.height)];
        [_codeBgView setViewEdgeWithBorderWidth:0.5 cornerRadius:3 borderColor:[UIColor grayColor]];
        
        _codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, _codeBgView.width-10, _codeBgView.height)];
        _codeTextField.placeholder = @"请输入短信验证码";
        _codeTextField.textColor = kTitleColor_light;
        _codeTextField.font = kFontMidden;
        _codeTextField.delegate = self;
        if (@available(iOS 13.0,*)) {
            Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
            UILabel *placeholderLabel = object_getIvar(_codeTextField, ivar);
            placeholderLabel.textColor = kTitleColor_light;
            placeholderLabel.font = [UIFont boldSystemFontOfSize:14];
        }else{
            [_codeTextField setValue:kTitleColor_light forKeyPath:@"_placeholderLabel.textColor"];
        }
        _codeTextField.keyboardType = UIKeyboardTypeNumberPad;
        _codeTextField.returnKeyType=UIReturnKeyDone;
        [_codeBgView addSubview:_codeTextField];

    }
    return _codeBgView;
}

- (UIView *)logBgView{
    
    if (nil == _logBgView) {
        
        _logBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _logoImageBgView.bottom, SCREEN_WIDTH, 290)];
        [_logBgView addSubview:self.accountBgView];
        [_logBgView addSubview:self.passwordBgView];
        [_logBgView addSubview:self.codeBgView];
        [self.codeBgView setHidden:YES];
        
        _sendMessageBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-76-20, self.passwordBgView.bottom+10, 70, 22)];
        [_sendMessageBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _sendMessageBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_sendMessageBtn setTitleColor:kTitleColor_midden forState:UIControlStateNormal];
        [_sendMessageBtn addTarget:self action:@selector(sendMessageClick:) forControlEvents:UIControlEventTouchUpInside];
        [_sendMessageBtn setHidden:YES];
        [_logBgView addSubview:_sendMessageBtn];
        
        UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, _sendMessageBtn.bottom + 10, _logBgView.width-60, 44)];
        loginBtn.layer.cornerRadius = 5;
        loginBtn.backgroundColor = UIColorFromRGB1(0xE5B580);
        [loginBtn setTitle:@"登     录" forState:UIControlStateNormal];
        [loginBtn setTitleColor:kTitleColor_black forState:UIControlStateNormal];
        [loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_logBgView addSubview:loginBtn];
        
        _pwdCodeSwitchBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, loginBtn.bottom + 20, 100, 30)];
        [_pwdCodeSwitchBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
        _pwdCodeSwitchBtn.centerX = self.view.centerX;
        _pwdCodeSwitchBtn.titleLabel.font = kFontMidden;
        [_pwdCodeSwitchBtn setTitleColor:kTitleColor_black forState:UIControlStateNormal];
        [_pwdCodeSwitchBtn addTarget:self action:@selector(pwdCodeSwitchBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_logBgView addSubview:_pwdCodeSwitchBtn];

    }
    return _logBgView;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _accountTextField) {
        NSMutableString *mutableStr = [NSMutableString stringWithString:_accountTextField.text];
        [mutableStr appendString:string];
        
        if (mutableStr.length > 11) {
//            [EFShowView showText:@"号码长度为11位"];
            return NO;
        }
    }
//    if ([string isEqualToString:@"\n"]) {
//        [textField resignFirstResponder];
//        return NO;
//    }
    return YES;
}

- (EFLoginModel *)loginModel{
    
    if (nil == _loginModel) {
        _loginModel = [[EFLoginModel alloc]initWithDelegate:self cache:NO];
    }
    return _loginModel;
}

- (EFCodeLoginModel *)codeLoginModel{
    
    if (nil == _codeLoginModel) {
        _codeLoginModel = [[EFCodeLoginModel alloc]initWithDelegate:self cache:NO];
    }
    return _codeLoginModel;
}

- (EFSendMsgModel *)msgModel{
    
    if (nil == _msgModel) {
        _msgModel = [[EFSendMsgModel alloc]initWithDelegate:self cache:NO];
    }
    return _msgModel;
}

- (EFTabBarController *)tabbar
{
    if (nil == _tabbar) {
        _tabbar = [[EFTabBarController alloc]init];
    }
    return _tabbar ;
}

- (NSString *)SHA256WithKey:(NSString *)srcString{

    const char *string = [srcString UTF8String];
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(string, (CC_LONG)strlen(string), result);

    NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
      [hashed appendFormat:@"%02x", result[i]];
    }
    NSLog(hashed);
    return hashed;

}

@end
























